//////////////////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2014-2015, Egret Technology Inc.
//  All rights reserved.
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of the Egret nor the
//       names of its contributors may be used to endorse or promote products
//       derived from this software without specific prior written permission.
//
//  THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
//  OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
//  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
//  IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
//  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
//  OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
//  EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////////////
//class Tween extends egret.Tween { }
class Main extends egret.DisplayObjectContainer {
    private static __instance: Main;
    public static getinstance(): Main {

        return this.__instance;
    }
    /**
     * 加载进度界面
     * Process interface loading
     */
    private loadingView: LoadingUI;
    private listResources = new Array(
        new Resources("Plane", "飞机模型"),
        new Resources("Bullet", "子弹模型"),
        new Resources("Bgm", "背景音乐"));
    public constructor() {
        super();
        this.addEventListener(egret.Event.ADDED_TO_STAGE, this.onAddToStage, this);
        this._lastTime = egret.getTimer();
    }

    private onAddToStage(event: egret.Event) {
        //设置加载进度界面
        //Config to load process interface
        this.loadingView = new LoadingUI();
        this.stage.addChild(this.loadingView);

        //初始化Resource资源加载库
        //initiate Resource loading library
        RES.addEventListener(RES.ResourceEvent.CONFIG_COMPLETE, this.onConfigComplete, this);
        RES.loadConfig("resource/default.res.json", "resource/");


    }

    /**
     * 配置文件加载完成,开始预加载Plane资源组。
     * configuration file loading is completed, start to pre-load the Plane resource group
     */
    private onConfigComplete(event: RES.ResourceEvent): void {

        RES.removeEventListener(RES.ResourceEvent.CONFIG_COMPLETE, this.onConfigComplete, this);
        RES.addEventListener(RES.ResourceEvent.GROUP_COMPLETE, this.onResourceLoadComplete, this);
        RES.addEventListener(RES.ResourceEvent.GROUP_LOAD_ERROR, this.onResourceLoadError, this);
        RES.addEventListener(RES.ResourceEvent.GROUP_PROGRESS, this.onResourceProgress, this);
        RES.addEventListener(RES.ResourceEvent.ITEM_LOAD_ERROR, this.onItemLoadError, this);

        for (var item in this.listResources) {
            var list: any = this.listResources[item];
            var resources: Resources = list;
            RES.loadGroup(resources.name);
        }
    }

    /**
     * Plane资源组加载完成
     * Preload resource group is loaded
     */
    private onResourceLoadComplete(event: RES.ResourceEvent): void {
        var isOver = false;
        var Road = RES.getRes("ditu_json");
        //  console.log(Road);
        Road.layers[1].DATA;
        //  console.log(Road.layers[1].DATA);
        for (var item in this.listResources) {
            var list: any = this.listResources[item];
            var resources: Resources = list;
            if (event.groupName == resources.name) {
                resources.isOver = true;
            }
            isOver = resources.isOver;
        }

        if (isOver) {
            this.stage.removeChild(this.loadingView);
            RES.removeEventListener(RES.ResourceEvent.GROUP_COMPLETE, this.onResourceLoadComplete, this);
            RES.removeEventListener(RES.ResourceEvent.GROUP_LOAD_ERROR, this.onResourceLoadError, this);
            RES.removeEventListener(RES.ResourceEvent.GROUP_PROGRESS, this.onResourceProgress, this);
            RES.removeEventListener(RES.ResourceEvent.ITEM_LOAD_ERROR, this.onItemLoadError, this);
            //背景
            this.bg = new DituExample();//创建背景
            this.addChild(this.bg);
            this.createGameScene();
        }
    }

    /**
     * 资源组加载出错
     *  The resource group loading failed
     */
    private onItemLoadError(event: RES.ResourceEvent): void {
        console.warn("Url:" + event.resItem.url + " has failed to load");
    }

    /**
     * 资源组加载出错
     *  The resource group loading failed
     */
    private onResourceLoadError(event: RES.ResourceEvent): void {
        //TODO
        console.warn("Group:" + event.groupName + " has failed to load");
        //忽略加载失败的项目
        //Ignore the loading failed projects
        this.onResourceLoadComplete(event);
    }

    /**
     * Plane资源组加载进度
     * Loading process of Plane resource group
     */
    private onResourceProgress(event: RES.ResourceEvent): void {
        for (var item in this.listResources) {
            var list: any = this.listResources[item];
            var resources: Resources = list;
            if (event.groupName == resources.name) {
                this.loadingView.setCustomProgress(event.itemsLoaded, event.itemsTotal, resources.chinese);
            }
        }
    }

    private textfield: egret.TextField;

    /**@private*/
    private _lastTime: number;

    /**触发主角开枪时间的间隔*/
    private planeShootTime: egret.Timer = new egret.Timer(500);

    /**触发创建敌机的间隔*/
    private enemyFightersTimer: egret.Timer = new egret.Timer(500);

    /*我方飞机*/
    private myfighter: Plane;

    /**触发敌人开枪时间的间隔*/
    private enemyShootTime: egret.Timer = new egret.Timer(1000);

    /**敌人的飞机*/
    private enemyFighterslist: Plane[] = [];


    /*子弹集合*/
    private Bulletlist: Bullet[] = [];


    /**可滚动背景*/
    private bg: DituExample;

    //背景音乐
    private sound: egret.Sound;

    private _channel: egret.SoundChannel;
    /**
     * 创建游戏场景
     * Create a game scene
     */
    private createGameScene(): void {
        this.start();
    }

    //游戏结束
    private GameOver(): void {
        //var over: egret.Sound = RES.getRes("game_over_mp3");
        // over.play(0, 1);
        //this._channel.stop();
        this._channel = null;
        this.planeShootTime.stop();
        this.enemyFightersTimer.stop();
        this.enemyShootTime.stop();
        /**触发主角开枪时间的间隔*/
        this.planeShootTime = null;
        /**触发创建敌机的间隔*/
        this.enemyFightersTimer = null;
        /**触发敌人开枪时间的间隔*/
        this.enemyShootTime = null;
        for (var item in this.enemyFighterslist) {
            this.removeChild(this.enemyFighterslist[item].Image);
        }
        this.enemyFighterslist = [];
        for (var item in this.Bulletlist) {
            this.removeChild(this.Bulletlist[item].Image);
        }
        this.Bulletlist = [];
        // this.bg.pause();//暂停滚动
        var lives = this.myfighter.lives;
        //this.removeChild(this.myfighter.Image);
        this.myfighter.Image = null;
        this.myfighter.lives = 0;//金币归零
        var overbg: egret.Bitmap = new egret.Bitmap(RES.getRes("gameover_png"));
        var backButton: egret.Bitmap = new egret.Bitmap(RES.getRes("btn_finish_png"));
        var label: egret.TextField = new egret.TextField();
        label.text = lives + "分";
        label.x = this.stage.stageWidth / 2 - label.width / 2;
        label.y = this.stage.stageHeight / 2;
        backButton.x = this.stage.stageWidth / 2 - backButton.width / 2;
        backButton.y = (this.stage.stageHeight / 2) + 80;
        var mapthis = this;
        backButton.touchEnabled = true;
        backButton.addEventListener(egret.TouchEvent.TOUCH_TAP, function (evt: egret.TouchEvent) {
            mapthis._lastTime = 0;
            mapthis.removeChild(overbg);
            mapthis.removeChild(label);
            mapthis.removeChild(backButton);
            mapthis.start.apply(mapthis);
        }, this);
        this.addChild(overbg);
        this.addChild(label);
        this.addChild(backButton);
    }

    //开始游戏
    public start(): void {
        /**地图开始滚动*/
        //this.bg.start();
        // this.sound = RES.getRes("game_music_mp3");
        // this._channel = this.sound.play(0, -1);

        /**触发主角开枪时间的间隔*/
        this.planeShootTime = new egret.Timer(500);
        /**触发创建敌机的间隔*/
        this.enemyFightersTimer = new egret.Timer(1000);
        /**触发敌人开枪时间的间隔*/
        this.enemyShootTime = new egret.Timer(1000);
        //初始化主角
        var buleplane = new Blueplane(this);
        var plane = buleplane.init(this);

        this.addChild(plane.Image);
        this.addEventListener(egret.Event.ENTER_FRAME, this.gameViewUpdate, this);
        this.myfighter = plane;
        this.myfighter.Image.anchorOffsetX = this.myfighter.Image.width / 2;//固定X轴的锚点 
        this.myfighter.Image.anchorOffsetY = this.myfighter.Image.height / 2;//固定Y轴的锚点       
        //主角移动
        document.addEventListener("keypress", e => {
            //console.log(66);
            //如果按下键盘，飞机位置不超过界限，飞机不为空执行下一步
            if (e.key == "w" && plane.Y > 23 && this.myfighter.Image != null) {
                if (this.myfighter.Image != null) {
                    this.myfighter.Image.rotation = 0;

                }
                this.myfighter.Y -= 10;
                this.myfighter.Image.y -= 10;
            }

            if (e.key == "s" && plane.Y < 496 && this.myfighter.Image != null) {
                if (this.myfighter.Image != null) {
                    this.myfighter.Image.rotation = 180;
                }
                this.myfighter.Y += 10;
                this.myfighter.Image.y += 10;
            }

            if (e.key == "a" && plane.X > 23 && this.myfighter.Image != null) {
                if (this.myfighter.Image != null) {
                    this.myfighter.Image.rotation = -90;
                }
                this.myfighter.X -= 10;
                this.myfighter.Image.x -= 10;
            }
            if (e.key == "d" && plane.X < 498 && this.myfighter.Image != null) {
                if (this.myfighter.Image != null) {
                    this.myfighter.Image.rotation = 90;
                }
                this.myfighter.X += 10;
                this.myfighter.Image.x += 10;
            }

        })


        //主角添加事件
        this.planeShootTime.addEventListener(egret.TimerEvent.TIMER, this.AddMyPlane, [this, plane]);
        this.planeShootTime.start();
        //敌人开火事件
        this.enemyShootTime.addEventListener(egret.TimerEvent.TIMER, this.enemyShootTimefun, this);
        this.enemyShootTime.start();
        //敌人添加事件
        this.enemyFightersTimer.addEventListener(egret.TimerEvent.TIMER, this.enemyFightersTimerfun, this);
        this.enemyFightersTimer.start();
    }
    public value: string;
    //四种子弹，按下对应键，调出对应子弹
    //添加主角开枪事件
    private AddMyPlane() {
        document.addEventListener("keypress", e => {
            if (e.key == "w" || e.key == "s" || e.key == "a" || e.key == "d") {
                this.value = e.key;
            }
            //  console.log(this.value);
            if (this.value == "w") {
                if (e.key == "j") {
                    var bullet = this[1].Shoot();
                    bullet.name = "PLAB";
                    this[0].Bulletlist.push(bullet);
                    this[0].addChild(bullet.Image);
                    bullet.bulletSound.play(0, 1);
                }
            }
            if (this.value == "s") {
                if (e.key == "j") {
                    var bullet = this[1].Shoot2();
                    bullet.name = "PLAB";
                    this[0].Bulletlist.push(bullet);
                    this[0].addChild(bullet.Image);
                    bullet.bulletSound.play(0, 1);
                }
            }
            if (this.value == "a") {
                if (e.key == "j") {
                    var bullet = this[1].Shoot3();
                    bullet.name = "PLAB";
                    this[0].Bulletlist.push(bullet);
                    this[0].addChild(bullet.Image);
                    bullet.bulletSound.play(0, 1);
                }
            }
            if (this.value == "d") {
                if (e.key == "j") {
                    var bullet = this[1].Shoot4();
                    this[0].Bulletlist.push(bullet);
                    bullet.name = "PLAB";
                    this[0].addChild(bullet.Image);
                    bullet.bulletSound.play(0, 1);
                }
            }

        })
    }


    //敌军子弹
    private enemyShootTimefun() {
        var i: number = 0;
        var theFighter: Plane;
        var enemyFighterCount: number = this.enemyFighterslist.length;
        for (i = 0; i < enemyFighterCount; i++) {
            theFighter = this.enemyFighterslist[i];
            var bullet = theFighter.diShoot();
            this.Bulletlist.push(bullet);
            this.addChild(bullet.Image);
        }
    }

    //加入敌军
    private enemyFightersTimerfun() {
        //加入敌军
        var enemyplaneClass = new Enemyplane(this);
        var x = Math.random() * (this.stage.width - 128);//随机坐标
        var enemyplane = enemyplaneClass.init(x, -100);
        this.enemyFighterslist.push(enemyplane);
        this.addChild(enemyplane.Image);
        var bullet = enemyplane.Shoot();
        this.Bulletlist.push(bullet);
        this.addChild(bullet.Image);


    }

    /*飞机碰撞检测*/
    private collision() {
        var bullet = this.Bulletlist;//子弹数组
        var drplane = this.enemyFighterslist;//敌人的飞机
        var myplan = this.myfighter;//自己飞机
        for (var i in bullet)
        // for (var i = 0; i < bullet.length; i++) 
        {
            //子弹等于玩家子弹
            if (bullet[i].Plane.Image == myplan.Image)
            // if (bullet[i].Plane.Image.name == "PLAB") 
            {
                for (var l in drplane)
                // for (var l = 0; l < drplane.length; l++) 
                {
                    var playbullet = new egret.Rectangle(bullet[i].X, bullet[i].Y, bullet[i].Image.width, bullet[i].Image.height);
                    var enemy = new egret.Rectangle(drplane[l].X, drplane[l].Y, drplane[l].Image.width, drplane[l].Image.height);
                    var myhit: boolean = playbullet.intersects(enemy);
                    if (myhit) {
                        //舞台删除子弹，敌军图片
                        this.removeChild(bullet[i].Image);
                        this.removeChild(drplane[l].Image);
                        // this.removeEventListener(egret.Event.ENTER_FRAME, this.gameViewUpdate, this);
                        //删除数组子弹。敌军图片
                        bullet.splice(bullet.indexOf(bullet[i]), 1);
                        drplane.splice(drplane.indexOf(drplane[l]), 1);
                        //  return;
                    }
                }
            }
            //敌军子弹
            else {
                var player = new egret.Rectangle(myplan.X, myplan.Y, myplan.Image.width, myplan.Image.height);
                // var dijunbullet = new egret.Rectangle(bullet[i].X, bullet[i].Y, bullet[i].Image.width, bullet[i].Image.height);
                var dijunbullet = new egret.Rectangle(bullet[i].X + 32, bullet[i].Y + 32, 2, 2);
                var isHit: boolean = player.intersects(dijunbullet);
                if (isHit) {
                    console.log("坦克   " + myplan.X + "   ", myplan.Y, "    子弹  " + (bullet[i].X) + "  ", (bullet[i].Y));
                    // 删除敌军子弹，玩家飞机图片
                    this.removeChild(bullet[i].Image);
                    this.removeChild(myplan.Image);

                    // 删除子弹数组子弹图片。监听画面更新事件
                    bullet.splice(bullet.indexOf(bullet[i]), 1);
                    this.removeEventListener(egret.Event.ENTER_FRAME, this.gameViewUpdate, this);
                    this.GameOver.apply(this);
                    return;
                }
            }
        }
        //     private collision() {
        //         var bullet = this.Bulletlist;
        //         var drplane = this.enemyFighterslist;//敌人的飞机
        //         var myplan = this.myfighter;
        //         var mybg = this.bg;
        //         for (var i in bullet) {

        //             if (bullet[i].Plane.Image != myplan.Image) {
        //                 if (myplan.Image != null) {
        //                     var isHit: boolean = myplan.Image.hitTestPoint(bullet[i].X, bullet[i].Y - 40, true);//
        //                     if (isHit) {
        //                         this.removeChild(bullet[i].Image);//子弹图片删除在品目上
        //                         bullet.splice(bullet.indexOf(bullet[i]), 1);//子弹的列表中也删除这个子弹   //  [i]下表),1删除几个                 
        //                         this.removeEventListener(egret.Event.ENTER_FRAME, this.gameViewUpdate, this);//让他删除监听事件
        //                         this.GameOver.apply(this);//游戏结束
        //                         return;
        //                     }
        //                 }
        //             }

        //             else {
        //                 for (var l in drplane) {
        //                     if (this.myfighter != null) {
        //                         var myHit: boolean = drplane[l].Image.hitTestPoint(this.myfighter.X, this.myfighter.Y, true);
        //                         if (myHit) {
        //                             this.removeChild(this.myfighter.Image);
        //                             this.removeEventListener(egret.Event.ENTER_FRAME, this.gameViewUpdate, this);
        //                             this.GameOver.apply(this);
        //                             return;
        //                         }
        //                     }
        //                     var isHit: boolean = drplane[l].Image.hitTestPoint(bullet[i].X, bullet[i].Y, true);
        //                     if (isHit) {
        //                         this.removeChild(bullet[i].Image);
        //                         bullet.splice(bullet.indexOf(bullet[i]), 1);
        //                         this.removeChild(drplane[l].Image);
        //                         drplane.splice(drplane.indexOf(drplane[l]), 1);
        //                         //this.myfighter.lives += 1;
        //                     }
        //                 }
        //             }
        //         }
    }


    /**游戏画面更新*/
    private gameViewUpdate(evt: egret.Event): void {
        //为了防止FPS下降造成回收慢，生成快，进而导致DRAW数量失控，需要计算一个系数，当FPS下降的时候，让运动速度加快
        var nowTime: number = egret.getTimer();
        //var noime: number = egret.getTimer();
        var fps: number = 1000 / (nowTime - (this._lastTime));
        this._lastTime = nowTime;
        var speedOffset: number = 60 / fps;
        /**
         * 统一子弹管理
         */
        var i: number = 0;
        var bullet: Bullet;
        var BulletsCount: number = this.Bulletlist.length;
        for (; i < BulletsCount; i++) {
            bullet = this.Bulletlist[i];
            if (bullet.Type == "UP") {

                // console.log(1);
                if (bullet.Y < 5) {
                    this.removeChild(bullet.Image);//删除
                    this.Bulletlist.splice(i, 1);
                    i--;
                    BulletsCount--;//子弹数组减1
                }
                bullet.Y -= 7 * speedOffset;
                bullet.Image.y -= 7 * speedOffset;
            }

            else if (bullet.Type == "Donw") {
                // console.log(2);
                if (bullet.Y > 518)
                // if (bullet.Y - bullet.Image.height > this.stage.stageHeight) 
                {
                    this.removeChild(bullet.Image);
                    this.Bulletlist.splice(i, 1);
                    i--;
                    BulletsCount--;
                }
                bullet.Y += 7 * speedOffset;
                bullet.Image.y += 7 * speedOffset;
            }
            else if (bullet.Type == "down") {
                //console.log(3);
                if (bullet.Y > 518) {
                    this.removeChild(bullet.Image);//删除
                    this.Bulletlist.splice(i, 1);
                    i--;
                    BulletsCount--;//子弹数组减1
                }
                bullet.Y += 7 * speedOffset;
                bullet.Image.y += 7 * speedOffset;
            }
            else if (bullet.Type == "left") {
                //console.log(3);
                if (bullet.X < 3) {
                    this.removeChild(bullet.Image);//删除
                    this.Bulletlist.splice(i, 1);
                    i--;
                    BulletsCount--;//子弹数组减1
                }
                bullet.X -= 7 * speedOffset;
                bullet.Image.x -= 7 * speedOffset;
            }
            else if (bullet.Type == "righ") {
                //console.log(3);
                if (bullet.X > 518) {
                    this.removeChild(bullet.Image);//删除
                    this.Bulletlist.splice(i, 1);
                    i--;
                    BulletsCount--;//子弹数组减1
                }
                bullet.X += 7 * speedOffset;
                bullet.Image.x += 7 * speedOffset;
            }


        }
        //敌人飞机运动
        // var nowTime: number = egret.getTimer();
        //  var i: number = 0;
        // var fps: number = 1000 / (nowTime - (this._lastTime));
        // this._lastTime = nowTime;
        // var speedOffset: number = 60 / fps;
        var theFighter: Plane;
        var enemyFighterCount: number = this.enemyFighterslist.length;
        for (i = 0; i < enemyFighterCount; i++) {
            theFighter = this.enemyFighterslist[i];
            if (theFighter.Y - theFighter.Image.height > this.stage.stageHeight) {
                this.removeChild(theFighter.Image);
                this.enemyFighterslist.splice(i, 1);
                i--;
                enemyFighterCount--;
            }
            theFighter.Y += 4 * speedOffset;
            theFighter.Image.y += 4 * speedOffset;
        }

        //碰撞器开关
        this.collision();
    }
}
